package com.oem.fragment.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    // 每个 baseUrl 只会有一个 Retrofit 实例
    private static final Map<String, Retrofit> retrofitInstances = new HashMap<>();

    public static Retrofit getClient(String baseUrl) {

        // ✅ 注册 LocalDateTime 格式化为 yyyy-MM-dd'T'HH:mm:ss
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, type, context) ->
                        new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))))
                .create();

        // 检查是否已经存在对应 baseUrl 的 Retrofit 实例
        if (!retrofitInstances.containsKey(baseUrl)) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            // 设置日志级别为 BODY，记录请求和响应的完整内容
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .retryOnConnectionFailure(true)  // 设置连接失败时的重试策略
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(gson))  //.addConverterFactory(GsonConverterFactory.create())  // 添加 Gson 转换器以处理 JSON 数据
                    .client(client)  // OkHttpClient 是 Retrofit 的底层 HTTP 客户端
                    .build();

            retrofitInstances.put(baseUrl, retrofit);
        }
        return retrofitInstances.get(baseUrl);
    }
}

